// pages/medical/dept/index.js
import {
  hospitalApi
} from "../../../utils/hospital-api";

import p from "wl-pinyin";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    loading: false,
    hosCode: '',
    depName: '',
    activeKey: 1,
    activeNames: ['1'],
    hosInfo: {},
    departments: [],
    chat:['(',')','（','）']
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const hosInfo = wx.getStorageSync('hospital')
    this.setData({
      hosCode: options.hosCode,
      hosInfo: hosInfo
    })
    wx.setNavigationBarTitle({
      title: hosInfo.HOSNAME
    })
    this.getDepartment();
  },
  // 搜索词变化事件
  keywordsChange(e) {
    this.setData({
      depName: e.detail,
    });
  },
  // 清楚关键字
  clearKeywords() {
    this.setData({
      depName: '',
    });
    this.getDepartment();
  },
  // 搜索逻辑
  search() {
    this.getDepartment();
  },
  // 获取部门列表数据
  getDepartment() {
    this.setData({
      loading: true
    })
    hospitalApi({
      method: 'getDepartment',
      data: JSON.stringify({
        hosCode: this.data.hosCode,
        depName: this.data.depName //模糊检索的字段
      })
    }).then(res => {
      const sortedResult = this.classifyByLetter(res.data);
      let indexList = []
      for (const key in sortedResult) {
        indexList.push(key)
      }
      this.setData({
        departments: sortedResult,
        indexList: indexList,
        loading: false
      })
    })
  },
  // 跳转到医生页面
  toPage(e) {
    const item = e.mark.item;
    if (item.DEPID) {
      wx.setStorageSync('dept', item); //保存选中的科室信息
      wx.navigateTo({
        url: `/pages/medical/doctor/index?deptId=${item.DEPID}&hosCode=${this.data.hosCode}`
      })
    } else {
      wx.showToast({
        title: '科室代码错误！',
        icon: 'error'
      })
    }
  },
  // 按字母分类
  classifyByLetter(list) {
    let result = {};

    // 分类
    list.forEach(item => {
      let one = this.removeAllParentheses(item.DEPNAME).charAt(0);
      const letter = p.getFirstLetter(one).charAt(0);
      // 创建分类
      if (!result[letter]) {
        result[letter] = [];
      }
      result[letter].push(item);
    });
    result = Object.fromEntries(
      Object.entries(result).sort(([a], [b]) => a.localeCompare(b))
    );
    return result;
  },
  removeAllParentheses(str) {
    return str.replace(/[（(][^）)]*[）)]/g, '').trim();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
})